package qf.dao.daoImpl;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import qf.dao.CartDao;
import qf.pojo.Cart;
import qf.utils.DBUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package qf.dao.daoImpl
 * @Description:
 * @Date 2022/5/25 16:49
 */
public class CartDaoImpl implements CartDao {
    private QueryRunner qr = new QueryRunner(DBUtil.getDateSource());


    @Override
    public Cart findCartByUidAndPid(Integer uid,Integer pid) {
        String sql = "select * from tb_cart where uid = ? and pid=?";
        try {
            return qr.query(sql, new BeanHandler<Cart>(Cart.class),uid,pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(Cart cart) {
        String sql = "update tb_cart set num=? , money=? where cid=?";
        try {
            qr. update(sql, cart.getNum(), cart.getMoney(), cart.getCid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void addCart(Cart cart) {
        String sql = "insert into tb_cart (uid,pid,num,money) values (?,?,?,?)";
        try {
            qr.update(sql,cart.getUid(),cart.getPid(),cart.getNum(),cart.getMoney());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<Cart> selectCartByUid(Integer uid) {
        String sql = "select * from tb_cart where uid=?";
        try {
            List<Cart> query = qr.query(sql, new BeanListHandler<Cart>(Cart.class), uid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public Cart selectCartByCid(Integer cid) {
        String sql = "select * from tb_cart where cid=?";
        try {
            return qr.query(sql, new BeanHandler<Cart>(Cart.class), cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void delete(Integer cid) {
        String sql = "delete from tb_cart where cid=?";
        try {
            qr.update(sql, cid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
